import {
  Controller,
  Post,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { Body } from '@nestjs/common/decorators';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiConsumes, ApiTags } from '@nestjs/swagger';
import { join } from 'path';
import { UploadDto } from './dto/upload.dto';
import { UploadService } from './upload.service';
import * as fs from 'fs';
import { HttpReslut } from 'src/common/result/http-reslut';
import { File } from '../entities/file.entity';

@ApiTags('文件上传')
@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post()
  @UseInterceptors(FileInterceptor('file'))
  @ApiConsumes('multipart/form-data')
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
    @Body() upload: UploadDto,
  ) {
    const fileName = `${new Date().getTime()}.${file.mimetype.split('/')[1]}`;
    const path: string = join(__dirname, '..', '../public/upload', fileName);
    return new Promise((rel) => {
      fs.writeFile(path, file.buffer, function (err) {
        if (err) {
          return rel(new HttpReslut<string>('上传出错', 31000, 'false'));
        }
        let result_file: File = new File();
        result_file.fileName = fileName;
        result_file.fileUrl = `http://101.43.97.15:3000/public/upload/${fileName}`;
        result_file.fileType = file.mimetype;
        return rel(new HttpReslut<File>(result_file));
      });
    });
  }
}
